package com.trace.basic;

import lombok.extern.slf4j.Slf4j;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * Created by denglw on 2020/1/11.<br/>
 * Desc: 经典线程安全问题示例
 */
 @Slf4j
@SuppressWarnings("AlibabaThreadPoolCreation")
public class ThreadSafe {

    private int value = 0;

    private void incr() {
        value++;
    }

    private int getValue() {
        return value;
    }

    public static void main(String[] args) throws InterruptedException {
        int cycle = 500_000;
        ThreadSafe threadSafe = new ThreadSafe();
        Callable<Void> callable = () -> {
            threadSafe.incr();
            return null;
        };
        List<Callable<Void>> callables = new LinkedList<>();
        for (int i = 0; i < cycle; i++) {
            callables.add(callable);
        }
        ExecutorService pool = Executors.newFixedThreadPool(5);
        List<Future<Void>> futures = pool.invokeAll(callables);
        log.info("future size: [{}]; value sum: [{}].", futures.size(), threadSafe.getValue());
        pool.shutdown();
    }

}
